<script setup>
import { ref, onMounted, computed } from 'vue'
import { WarningFilled, CircleCheckFilled } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import { getUser, getOrder, getUserIndicatorResults } from '../../api/user'
import { listDoctors, listIndicators, listPackages } from '../../api/admin'
import { useAuthStore } from '../../store/auth'

const route = useRoute()
const auth = useAuthStore()
const loading = ref(false)
const order = ref(null)
const user = ref(null)
const results = ref([])
const total = ref(0)
const doctorNameMap = ref({})
const indicatorMap = ref({})
const packageNameMap = ref({})
const orderId = computed(() => Number(route.query.orderId) || null)
const statusMap = { 1: '待确认', 2: '已确认', 3: '已完成', 4: '已取消' }
const abnormalText = (row) => {
  if (!row?.abnormalFlag) return '正常'
  const ind = indicatorMap.value[row.indicatorId]
  const val = Number(row.resultValue)
  if (ind && !Number.isNaN(val)) {
    if (ind.upperLimit != null && val > ind.upperLimit) return '异常偏高'
    if (ind.lowerLimit != null && val < ind.lowerLimit) return '异常偏低'
  }
  return '异常'
}

const fetchBaseMaps = async () => {
  const [dsRes, indsRes, psRes] = await Promise.allSettled([
    listDoctors({ page: 1, size: 200 }),
    listIndicators({ page: 1, size: 500 }),
    listPackages({ page: 1, size: 200 })
  ])
  if (dsRes.status === 'fulfilled') {
    doctorNameMap.value = Object.fromEntries((dsRes.value.list || []).map(d => [d.doctorId, d.name]))
  }
  if (indsRes.status === 'fulfilled') {
    indicatorMap.value = Object.fromEntries((indsRes.value.list || []).map(i => [i.indicatorId, i]))
  }
  if (psRes.status === 'fulfilled') {
    packageNameMap.value = Object.fromEntries((psRes.value.list || []).map(p => [p.packageId, p.packageName]))
  }
}

const fetchReport = async () => {
  if (!orderId.value) return
  loading.value = true
  try {
    const [u, o, r] = await Promise.all([
      getUser(auth.currentId),
      getOrder(orderId.value),
      getUserIndicatorResults(auth.currentId, { orderId: orderId.value, page: 1, size: 500 })
    ])
    user.value = u || null
    order.value = o || null
    results.value = (r.list || [])
    total.value = r.total || results.value.length
  } finally { loading.value = false }
}

onMounted(async () => {
  await fetchBaseMaps()
  await fetchReport()
})
</script>

<template>
  <el-card>
    <template v-if="orderId && order">
    <h3>体检报告封面信息</h3>
    <el-descriptions :column="1" border class="mb-2">
      <el-descriptions-item label="姓名">{{ user?.name || user?.username || '-' }}</el-descriptions-item>
      <el-descriptions-item label="性别">{{ user?.gender || '-' }}</el-descriptions-item>
      <el-descriptions-item label="年龄">{{ user?.age ?? '-' }}</el-descriptions-item>
      <el-descriptions-item label="体检日期">{{ order?.orderDate || '-' }}</el-descriptions-item>
      <el-descriptions-item label="套餐名称">{{ packageNameMap[order?.packageId] || (order?.orderType==='INDICATOR' ? '单项体检' : '-') }}</el-descriptions-item>
      <el-descriptions-item label="主检医生">{{ doctorNameMap[order?.doctorId] || '-' }}</el-descriptions-item>
      <el-descriptions-item label="状态">{{ statusMap[order?.status] || order?.status || '-' }}</el-descriptions-item>
      <el-descriptions-item label="医生评语">{{ order?.remark || '-' }}</el-descriptions-item>
    </el-descriptions>

    <h3>体检结果明细表</h3>
    <el-table :data="results" v-loading="loading" style="width:100%">
      <el-table-column label="序号" width="70">
        <template #default="{ $index }">{{ $index + 1 }}</template>
      </el-table-column>
      <el-table-column label="检查项目">
        <template #default="{ row }">{{ indicatorMap[row.indicatorId]?.indicatorName || '-' }}</template>
      </el-table-column>
      <el-table-column label="指标代码" width="120">
        <template #default="{ row }">{{ indicatorMap[row.indicatorId]?.indicatorCode || '-' }}</template>
      </el-table-column>
      <el-table-column prop="resultValue" label="检查结果" width="120" />
      <el-table-column label="参考范围" width="160">
        <template #default="{ row }">
          {{ indicatorMap[row.indicatorId]?.lowerLimit }} - {{ indicatorMap[row.indicatorId]?.upperLimit }}
        </template>
      </el-table-column>
      <el-table-column label="单位" width="100">
        <template #default="{ row }">{{ indicatorMap[row.indicatorId]?.unit || '-' }}</template>
      </el-table-column>
      <el-table-column label="是否异常" width="140">
        <template #default="{ row }">
          <el-tag :type="row.abnormalFlag ? 'danger' : 'success'" effect="dark">
            <el-icon class="mr-1">
              <component :is="row.abnormalFlag ? WarningFilled : CircleCheckFilled" />
            </el-icon>
            {{ abnormalText(row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="doctorComment" label="医生点评" />
    </el-table>
    </template>
    <template v-else>
      <el-empty description="请选择体检记录并点击“查看报告”" />
    </template>
  </el-card>
</template>

<style scoped>
.mb-2{ margin-bottom:12px; }
</style>